<template>
  <span class="app-upload-file-wrap">
    <el-button type="primary" @click="handleClick">选择文件</el-button>
    <input type="file" hidden @change="handleChangeFile" ref="fileInput">
    <span :class="['file-name', fileInfo.fileId ? 'has-file-id' : '']" @click="handleClickFileName">{{
        fileInfo.text
      }}</span>
    <el-icon class="clear" @click="handleClickClear" v-if="fileInfo.fileId">
      <CircleClose/>
    </el-icon>
    <el-button v-if="isTest" @click="handleTest">测试</el-button>
  </span>
</template>
<script setup>
import {ref, reactive, defineEmits} from 'vue'
import {ElIcon, ElButton} from 'element-plus'
import {CircleClose} from '@element-plus/icons-vue'
import {getFile, uploadFile} from '@/utils/common/upload'
import {tip} from '@tip'

const emits = defineEmits(['uploaded'])
defineOptions({
  name: 'UploadFile',
})
// test
const isTest = ref(localStorage.getItem('isTest') === '1')

function handleTest() {
  emits('uploaded', {fileId: ('testId' + Math.random()).replace('.', '')})
  tip({message: '测试上传成功', type: 'success'})
}

// test end
const fileInput = ref()
const fileInfo = reactive({
  fileName: '',
  fileId: '',
  status: 1,
  text: '',
})

function handleClick() {
  fileInput.value.click()
}

async function handleChangeFile(e) {
  const file = e.target.files[0]
  if (file) {
    fileInfo.text = '上传中...'
    fileInfo.fileId = ''
    fileInfo.fileUrl = ''

    const res = await uploadFile({file})

    fileInfo.text = file.name
    fileInfo.fileId = res

    fileInfo.fileUrl = await getFile(res)

    emits('uploaded', fileInfo)
  }
}

function handleClickFileName() {
  window.open(fileInfo.fileUrl, '_blank')
}

function handleClickClear() {
  fileInput.value.value = ''
  fileInfo.text = ''
  fileInfo.fileId = ''
  fileInfo.fileUrl = ''
}
</script>
<style lang="less" scoped>
.app-upload-file-wrap {
  display: flex;
  gap: 8px;
  align-items: center;

  .file-name.has-file-id {
    color: var(--el-color-primary);
    cursor: pointer;
    text-decoration: underline;
  }

  .clear {
    cursor: pointer;
  }
}
</style>
